package com.wn.class30.cotroller.houtai;


import com.wn.class30.entity.*;
import com.wn.class30.entity.AdminUser;
import com.wn.class30.service.BackProductService;
import com.wn.class30.service.BusinessService;
import com.wn.class30.service.ProductImgDetailService;
import com.wn.class30.service.ProductImgHeadService;
import com.wn.class30.tools.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
public class BackProductController {
    @Resource
    private BackProductService backProductService;

    @Resource
    private ProductImgHeadService productImgHeadService;

    @Resource
    private BusinessService businessService;

    @Resource
    private ProductImgDetailService productImgDetailService;

    private Map<Integer,Product> productMap = new HashMap<>();

    private Map<Integer,Integer> isUpdateHeadImg = new HashMap<>();

    private Map<Integer,Integer> isUpdateDetailImg = new HashMap<>();

    private Map<Integer,Integer> isUpdateProductImg = new HashMap<>();

    @RequestMapping("/houtai/page/products/product/getAllBusiness")
    public Result getAllBusiness(){
        return new Result("200","success",null,backProductService.getAllBusiness());
    }
    @RequestMapping("/houtai/page/products/product/getAllProTypes")
    public Result getAllProTypes(){
        return new Result("200","success",null,backProductService.getAllProTypes());
    }
    @RequestMapping("/houtai/page/products/product/list")
    @RequiresPermissions("/houtai/page/products/product/list")
    public Result getList(){
        return new Result("200","success",null,null);
    }

    @RequestMapping("/houtai/products/getProducts")
    public Result getProductsByPage(Integer page,Integer limit,String name, String proCode, String status,String businessName,String proType){
        Subject subject = SecurityUtils.getSubject();
        AdminUser adminUser = (AdminUser)subject.getPrincipal();
        Integer businessId = adminUser.getBusinessId();
        Map<String,String> map = new HashMap<>();
        map.put("page",String.valueOf(page));
        map.put("limit",String.valueOf(limit) );
        map.put("name", name);
        map.put("proCode", proCode);
        map.put("status", status);
        map.put("businessName", businessName);
        map.put("proType", proType);
        Page pager = new Page();
        pager.setCurrentPage(page);
        pager.setPageSize(limit);
        if(businessId != 0){
            map.put("businessId",businessId+"");
        }
        int count = backProductService.selectCount((HashMap) map);
        pager.setTotalSize(count);
        pager.setTotalPage(count%limit==0?count/limit:count/limit+1);
        return new Result("0","success",pager, (List) backProductService.select((HashMap) map));

    }
    @RequiresPermissions("/houtai/page/products/product/delete")
    @RequestMapping("/houtai/page/products/product/delete")
    public Result deleteProductById(@NotNull String productIds)throws Exception{
        System.out.println(productIds);
        if(productIds != null && !"".equals(productIds.trim())){
            if(productIds.indexOf("[")!=-1){
                Integer[] array = StringToArray.getArray(productIds);
                for (Integer integer : array) {
                    //从服务器删除商品展示图
                    QiniuUtil.deleteImg(backProductService.selectProductById(integer).getProductImg());
                    //从服务器删除轮播图
                    List<ProductImgHead> productImgHeads = productImgHeadService.selectProductImgHeadsByProductId(integer);
                    if(productImgHeads.size() > 0){
                        for (ProductImgHead productImgHead : productImgHeads) {
                            QiniuUtil.deleteImg(productImgHead.getProductImgHeadUrl());
                        }
                    }

                    //从服务器删除商品详情图
                    List<ProductImgDetail> productImgDetails = productImgDetailService.selectProductImgDetailsByProductId(integer);
                    if(productImgDetails.size() > 0){
                        for (ProductImgDetail productImgDetail : productImgDetails) {
                            QiniuUtil.deleteImg(productImgDetail.getProductImgDetailUrl());
                        }
                    }
                    //数据库删除该商品对应的商品轮播图
                    productImgHeadService.deleteProductImgHeadByProductId(integer);
                    //数据库删除该商品对应的商品详情图
                    productImgDetailService.deleteProductImgDetailByProductId(integer);
                    //删除商品
                    backProductService.deleteProductById(integer);
                }
            }else{
                backProductService.deleteProductById(Integer.parseInt(productIds));
            }

            return new Result("200","success",null,null);
        }
        return new Result("500","error",null,null);
    }

    /**
     * 后台点击更新按钮，把数据存入到map里面，方便更新页面从map取值
     * @param productId
     * @return
     * @throws Exception
     */
    @RequestMapping("/houtai/page/products/product/update")
    @RequiresPermissions("/houtai/page/products/product/update")
    public Result saveProductInSession(Integer productId)throws Exception{
        log.info("productId ================== "+productId);
        if(productId != null){
            Subject subject = SecurityUtils.getSubject();
            AdminUser adminUser = (AdminUser) subject.getPrincipal();
            Product product = backProductService.selectProductById(productId);
            product.setProductImgHeads(productImgHeadService.selectProductImgHeadsByProductId(product.getProductId()));
            product.setProductImgDetails(productImgDetailService.selectProductImgDetailsByProductId(product.getProductId()));
            productMap.put(adminUser.getAdminUserId(),product);
            return new Result("200","success",null,null);
        }
        return new Result("500","error",null,null);
    }

    /**
     * 更新页面初始化时发送请求向后台取值
     * @return
     * @throws Exception
     */
    @RequestMapping("/houtai/page/products/product/getSession")
    @RequiresPermissions("/houtai/page/products/product/update")
    public Result getProductInSessinByAdminUserId()throws Exception{
        Subject subject = SecurityUtils.getSubject();
        AdminUser adminUser = (AdminUser) subject.getPrincipal();
        Product product = productMap.get(adminUser.getAdminUserId());
        if(product != null){
            return new Result("200","success",product,null);
        }
        return new Result("500","error",null,null);
    }

    /**
     * 确认修改按钮提交
     * @param product
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/houtai/page/products/product/sureUpdate",method = RequestMethod.POST)
    @RequiresPermissions("/houtai/page/products/product/update")
    public Result sureUpdate(@RequestBody Product product)throws Exception{
        System.out.println(product);
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        AdminUser adminUser = (AdminUser) subject.getPrincipal();
        //获取当前登录用户是否修改了图片，未修改value值为0，修改了value值为1
        Integer productImg = isUpdateProductImg.get(adminUser.getAdminUserId());
        Integer headImg = isUpdateHeadImg.get(adminUser.getAdminUserId());
        Integer detailImg = isUpdateDetailImg.get(adminUser.getAdminUserId());
        log.info("productImg================"+productImg);
        log.info("headImg================"+headImg);
        log.info("detailImg================"+detailImg);
        log.info("productImg==============="+product.getProductImg());
        Product oldProduct = backProductService.selectProductById(product.getProductId());
        //如果用户修改了商品展示图
        if(oldProduct.getProductImg() != null && !"".equals(oldProduct.getProductImg()) && productImg != null && productImg > 0){
            //删除七牛云上的图片
            QiniuUtil.deleteImg(oldProduct.getProductImg().split("com/")[1]);
            //通过key移除map，避免map一直增长
            isUpdateProductImg.remove(adminUser.getAdminUserId());
        }

        //如果用户修改过轮播图
        if(product.getProductImgHeads().size() > 0 && headImg != null && headImg > 0){
            //删除服务器上的原轮播图
            List<ProductImgHead> productImgHeads1 = productImgHeadService.selectProductImgHeadsByProductId(product.getProductId());
            for (ProductImgHead productImgHead : productImgHeads1) {
                //删除七牛云上原轮播图
                if (productImgHead.getProductImgHeadUrl() != null && !"".equals(productImgHead.getProductImgHeadUrl())){
                    QiniuUtil.deleteImg(productImgHead.getProductImgHeadUrl().split("com/")[1]);
                }
                //通过key移除掉map
                isUpdateHeadImg.remove(adminUser.getAdminUserId());
            }
            //删除数据库原有轮播图记录
            productImgHeadService.deleteProductImgHeadByProductId(product.getProductId());
            //再把新的轮播图路径存入数据库
            List<ProductImgHead> productImgHeads = product.getProductImgHeads();
            for (ProductImgHead productImgHead : productImgHeads) {
                productImgHeadService.insertProductImgHead(productImgHead);
            }
        }

        //如果用户修改过商品详情图
        if(product.getProductImgDetails().size() > 0 && detailImg != null && detailImg > 0){
            //删除服务器上原商品详情图
            List<ProductImgDetail> list = productImgDetailService.selectProductImgDetailsByProductId(product.getProductId());
            for (ProductImgDetail productImgDetail : list) {
                if (productImgDetail.getProductImgDetailUrl() != null && !"".equals(productImgDetail.getProductImgDetailUrl())){
                    QiniuUtil.deleteImg(productImgDetail.getProductImgDetailUrl().split("com/")[1]);
                }
                isUpdateDetailImg.remove(adminUser.getAdminUserId());
            }
            //删除数据库原有商品详情图记录
            productImgDetailService.deleteProductImgDetailByProductId(product.getProductId());
            //把新的商品详情图存入数据库
            List<ProductImgDetail> productImgDetails = product.getProductImgDetails();
            for (ProductImgDetail productImgDetail : productImgDetails) {
                log.info("开始插入商品详情图。。。。。。。。。。。。。。");
                log.info("商品详情对象=========="+productImgDetail);
                productImgDetailService.insertProductImgDetail(productImgDetail);
            }
        }
        backProductService.updateProductById(product);
        //修改成功后通过key移除map，避免map一直无穷增长
        productMap.remove(adminUser.getAdminUserId());
        return new Result("200","success",null,null);
    }

    /**
     * 新增商品
     * @param product
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/houtai/page/products/product/insert",method = RequestMethod.POST)
    @RequiresPermissions("/houtai/page/products/product/insert")
    public Result insertProduct(@RequestBody Product product)throws Exception{
        Subject subject = SecurityUtils.getSubject();
        AdminUser adminUser = (AdminUser) subject.getPrincipal();
        System.out.println("product==================="+product);
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = simpleDateFormat.format(new Date());
        //获取店铺名称首字母大写
        ChineseToFirstLetterUtil chineseToFirstLetterUtil = new ChineseToFirstLetterUtil();
        Business business = businessService.selectBusinessById(adminUser.getBusinessId());
        log.info(business+"");
        //商品编码规则：店铺首字母大写+当前时间，避免商品编号重复
        product.setProductCode(chineseToFirstLetterUtil.getAllFirstLetter(business.getBusinessName())+format);
        //设置当前登录商家ID
        product.setBusinessId(adminUser.getBusinessId());
        Integer productId = backProductService.insertProduct(product);
        if(product != null){
            product.setBusinessId(adminUser.getBusinessId());
            if(product.getProductImgHeads().size() > 0){
                List<ProductImgHead> productImgHeads = product.getProductImgHeads();
                for (ProductImgHead productImgHead : productImgHeads) {
                    productImgHead.setProductId(productId);
                    productImgHeadService.insertProductImgHead(productImgHead);
                }
            }
            if(product.getProductImgDetails().size() > 0){
                List<ProductImgDetail> productImgDetails = product.getProductImgDetails();
                for (ProductImgDetail productImgDetail : productImgDetails) {
                    productImgDetail.setProductId(productId);
                    productImgDetailService.insertProductImgDetail(productImgDetail);
                }
            }

            return new Result("200","success",null,null);
        }else{
            return new Result("500","error",null,null);
        }
    }



    /**
     * 上传商品展示图
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/houtai/page/products/product/uploadProductImg")
    public Result uploadProductImg(MultipartFile file)throws Exception{
        if(!file.isEmpty()){
            String filename = file.getOriginalFilename();
            log.info("图片上传顺序==============================="+filename);
            String returnName = filename.substring(0,filename.lastIndexOf("."));
            log.info("returnName============================="+returnName);
            //取出文件名的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            System.out.println("文件后缀名"+suffix);
            //利用UUID生成一个不重复的文件名，避免文件名重复覆盖掉源文件
            UUID uuid = UUID.randomUUID();
            String newFileName = uuid+suffix;
            QiniuUtil.upload(newFileName,file.getInputStream());
            String imgPath = QiniuUtil.fullPath(newFileName);
            Subject subject = SecurityUtils.getSubject();
            AdminUser adminUser = (AdminUser) subject.getPrincipal();
            isUpdateProductImg.put(adminUser.getAdminUserId(),1);
            return new Result("200",imgPath+"||"+returnName,null,null);
        }
        return new Result("500","error",null,null);
    }

    /**
     * 上传轮播图
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/houtai/page/products/product/uploadHeadImg")
    public Result uploadHeadImg(MultipartFile file)throws Exception{
        if(!file.isEmpty()){
            String filename = file.getOriginalFilename();
            log.info("图片上传顺序==============================="+filename);
            String returnName = filename.substring(0,filename.lastIndexOf("."));
            log.info("returnName============================="+returnName);
            //取出文件名的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            System.out.println("文件后缀名"+suffix);
            //利用UUID生成一个不重复的文件名，避免文件名重复覆盖掉源文件
            UUID uuid = UUID.randomUUID();
            String newFileName = uuid+suffix;
            QiniuUtil.upload(newFileName,file.getInputStream());
            String imgPath = QiniuUtil.fullPath(newFileName);
            Subject subject = SecurityUtils.getSubject();
            AdminUser adminUser = (AdminUser) subject.getPrincipal();
            isUpdateHeadImg.put(adminUser.getAdminUserId(),1);
            return new Result("200",imgPath+"||"+returnName,null,null);
        }
        return new Result("500","error",null,null);
    }


    /**
     * 上传商品详情图
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/houtai/page/products/product/uploadDetailImg")
    public Result uploadDetailImg(MultipartFile file)throws Exception{
        if(!file.isEmpty()){
            String filename = file.getOriginalFilename();
            log.info("图片上传顺序==============================="+filename);
            String returnName = filename.substring(0,filename.lastIndexOf("."));
            log.info("returnName============================="+returnName);
            //取出文件名的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            System.out.println("文件后缀名"+suffix);
            //利用UUID生成一个不重复的文件名，避免文件名重复覆盖掉源文件
            UUID uuid = UUID.randomUUID();
            String newFileName = uuid+suffix;
            QiniuUtil.upload(newFileName,file.getInputStream());
            String imgPath = QiniuUtil.fullPath(newFileName);
            Subject subject = SecurityUtils.getSubject();
            AdminUser adminUser = (AdminUser) subject.getPrincipal();
            isUpdateDetailImg.put(adminUser.getAdminUserId(),1);
            return new Result("200",imgPath+"||"+returnName,null,null);
        }
        return new Result("500","error",null,null);
    }

}
